﻿/*  
cd /projects/hsieh_project/proj_201809/code_1_data/
qsas data_1_aux.sas 5 &
*/

libname lbd "/projects/data_commons/lbd/";
libname hr "/projects/hsieh_project/proj_201809/data/";

%Let dir_out = /projects/hsieh_project/proj_201809/data/;


/*---------------------------------------------------------*/
/* Load Raw Data */
/*---------------------------------------------------------*/

%macro m_read(param_dev= );

%if &param_dev. = 0 %then %do;

%put --------------------------------------------------------------------------------;
%put All Years, Final Run;
%Global c_keep_year;
%Let c_keep_year=%quote( );
%include "/projects/hsieh_project/proj_201809/code_1_data/data_0_read_raw.sas" /source2;

%end;
%else %do;

%put --------------------------------------------------------------------------------;
%put Selected Years, For Development;
data lbd;
  set hr.lbd_all;
run;

%end;

%mend;

%m_read(param_dev=1);

/*
--------------------------------------------------------------------------------
Select firms with auxiliary establishments
*/

data dt_aux;
  set lbd.lbd_raw_fk_aux;
run;

proc sort data=lbd; by year lbdid;
proc sort data=dt_aux; by year lbdid;

data dt_firm;
  merge lbd(in=in_main) dt_aux(in=in_aux);
  by year lbdid;
  if in_main;
  if in_aux;
run;

proc sort data=dt_firm; by year firmnum;
data dt_firm;
  set dt_firm;
  by year firmnum;
  if first.firmnum;
  with_aux=1;
  keep year firmnum;
run;
  
data dt_out;
  merge lbd(in=in_main) dt_aux;
  by year lbdid;
  if in_main;
run;

proc sort data=dt_out; by year firmnum;
proc sort data=dt_firm; by year firmnum;

data dt_out;
  merge dt_out(in=in_main) dt_firm(in=in_firm);
  by year firmnum;
  if in_main;
  if in_firm;
run;

/*
--------------------------------------------------------------------------------
Export I
*/

data dt_agg;
  set dt_out;
run;

proc sort data=dt_agg; by year fk_naics ch_ind aux_fk_naics aux_ch_ind;

proc means data=dt_agg noprint;
  by year fk_naics ch_ind aux_fk_naics aux_ch_ind;
  output out=dt_agg sum(worker est salary) = worker est salary;
run;

proc export data=dt_agg outfile="&dir_out./lbd_aux_agg.dta" replace;
run;

/*
--------------------------------------------------------------------------------
Export II
*/

data dt_out;
  set dt_out;
  if year in (1977,1982,1987,1992,1997,2000,2001);
  run;
run;

data hr.lbd_aux;
  set dt_out;
run;

proc export data=dt_out outfile="&dir_out./lbd_aux.dta" replace;
run;

/* End of SAS file */
